#include "capp.h"
#include <iostream>
#ifdef WIN_32
#include "sleep.h"
#else
  #include <unistd.h>
#endif

using namespace std;

TurnStateT CApp::turnState = PLAYER_IDLE;

CApp::CApp() {
  cout << "CApp ctor" << endl;
  Surf_Display = NULL;
 
  Running = true;
}
 
int CApp::Execute() {
  cout << "CApp :: Execute" << endl;
  if(Init() == false) {
    return -1;
  }

  SDL_Event evnt;

  while(Running) {
    while(SDL_PollEvent(&evnt)) {
      OnEvent(&evnt);
    }

    Loop();
    Render();
  }

  Cleanup();

  return 0;
}
 
bool CApp::Init() {
//   cout << "CApp::Init" << endl;
  if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
    return false;
  }

  if((Surf_Display = SDL_SetVideoMode(WWIDTH, WHEIGHT, 32, SDL_HWSURFACE | SDL_DOUBLEBUF)) == NULL) {
    return false;
  }
  
  if(entity1.Load("../gfx/yoshi.bmp", TILE_SIZE, TILE_SIZE, 8) == false) {
      return false;
  }
  
  if(entity2.Load("../gfx/yoshi.bmp", TILE_SIZE, TILE_SIZE, 8) == false) {
      return false;
  }
  
  entity1.x = 150;
  entity1.y = 70;
  entity1.cellX = 2;
  entity1.cellY = 1;
  
  entity2.x = 200;
  entity2.y = 150;
  
  Entity::EntityList.push_back(&entity1);
  Entity::EntityList.push_back(&entity2);
  
  turnState = PLAYER_IDLE;
  if (gameField.Load("../maps/1.map") == false){
      return false;
  }
  
  return true;
}
 
void CApp::OnEvent(SDL_Event* evnt) {
  //cout << "CApp::OnEvent" << endl;
  Event::OnEvent(evnt);
}

void CApp::Exit() {
//   cout << "CApp::Exit" << endl;
  Running = false;
}
 
void CApp::Loop() {
  //cout << "CApp::Loop" << endl;
  for (int i = 0; i < Entity::EntityList.size(); i++){
    if(!Entity::EntityList[i]){
      continue;
    }
    Entity::EntityList[i]->Loop();
  }
  
#ifdef WIN_32
  Sleep(100);
#else
  usleep(100000);
#endif
}
 
void CApp::Render() {
  //cout << "CApp::Render" << endl;
  gameField.Draw(Surf_Display);
  for (int i = 0; i < Entity::EntityList.size(); i++){
    if(!Entity::EntityList[i]){
      continue;
    }
    Entity::EntityList[i]->Render(Surf_Display);
  }
  
  SDL_Flip(Surf_Display);
}
 
void CApp::Cleanup() {
//   cout << "CApp::Render" << endl;
  SDL_FreeSurface(Surf_Display);
  for (int i = 0; i < Entity::EntityList.size(); i++){
    if(!Entity::EntityList[i]){
      continue;
    }
    Entity::EntityList[i]->Render(Surf_Display);
  }
  Entity::EntityList.clear();
  SDL_Quit();
}

void CApp::OnLButtonDown(int mX, int mY) {
  gameField.OnLButtonDown(mX, mY);
}


